import Cell from './Cell.js'

class Snake {
    constructor (x, y, size, color = '#7bed9f') {
        this.color = color
        this.head = new Cell(x, y, size, color)
        this.foo = this.head
        this.len = 1
    }

    draw(ctx) {
        let curr = this.head
        while (curr != null) {
            curr.draw(ctx)
            curr = curr.next
        }
    }

    eat(cell) {
        let curr = this.head
        while (curr.next != null)
            curr = curr.next
        
        cell.color = this.color // 统一颜色
        cell.prev = curr
        curr.next = cell // 追加节点
        this.foo = cell
        this.len ++
        let list = this.toList()
        // console.warn(list);
    }

    moveUp() {
        // console.log(`move up`);
        let curr = this.foo
        // console.log(`${curr.x} ${curr.y}`);
        while (curr.prev) {
            // console.log(`${curr.x} ${curr.y}`);
            curr.x = curr.prev.x
            curr.y = curr.prev.y
            curr = curr.prev
        }
        curr.y--
        // console.log(this);
    }

    moveDown() {
        // console.log(`move down`);
        let curr = this.foo
        while (curr.prev) {
            curr.x = curr.prev.x
            curr.y = curr.prev.y
            curr = curr.prev
        }
        curr.y++
    }
    
    moveLeft() {
        // console.log(`move left`);
        let curr = this.foo
        // console.log(`${curr.x} ${curr.y}`);
        while (curr.prev) {
            curr.x = curr.prev.x
            curr.y = curr.prev.y
            curr = curr.prev
        }
        curr.x--
        // console.log(this);
    }

    moveRight() {
        // console.log(`move right`);
        let curr = this.foo
        while (curr.prev) {
            // console.log(`${curr.x} ${curr.y}`);
            curr.x = curr.prev.x
            curr.y = curr.prev.y
            curr = curr.prev
        }
        curr.x++
    }

    toList() {
        const list = []
        let curr = this.head
        while (curr) {
            list.push(curr)
            curr = curr.next
        }
        return list
    }


}

export default Snake